﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WMS.HelperClasses;
using WHMS.HelperClasses;
using WHMS.TypedListClasses;
using SD.LLBLGen.Pro.ORMSupportClasses;
using WHMS;
using WHMS.EntityClasses;

namespace WMS
{
	public partial class PricingForm : Form
	{
		public PricingForm()
		{
			InitializeComponent();

			LoadData();
		}

		private void LoadData()
		{
			FormsHelper.LoadComboBox(TransactionsDDL, TransactionFields.Id, TransactionFields.PermitNumber, () => Business.GetUnpricedDepositTransactions());
		}

		private int GetSelectedTransactionId()
		{
			return (int)((System.Data.DataRowView)(TransactionsDDL.SelectedItem)).Row.ItemArray[0];
		}

		private void PricingDone_Click(object sender, EventArgs e)
		{
			SaveBtn.PerformClick();
			//_transactionItemForm.ValidateData();

			if (!_transactionItemForm.IsDataValid())
				return;

			Business.PricingDepositsDone(GetSelectedTransactionId());

			LoadData();
		}

		private void TransactionsDDL_SelectedIndexChanged(object sender, EventArgs e)
		{
			ResetTransactionItems();
		}

		DataMngrFormBase<TransactionItemEntity> _transactionItemForm;
		private void ResetTransactionItems()
		{
			if (_transactionItemForm != null)
			{
				_transactionItemForm.Dispose();
				_transactionItemForm = null;
			}

			var prefetch = new PrefetchPath2(EntityType.TransactionItemEntity);
			prefetch.Add(TransactionItemEntity.PrefetchPathItem).SubPath.Add(ItemEntity.PrefetchPathUnit_);

			_transactionItemForm = new DataMngrFormBase<TransactionItemEntity>(_transactionItems, dataGridView1, _transactionItemsBS, SaveBtn, SaveResult, new Label(), new RelationPredicateBucket(TransactionItemFields.TransactionId == GetSelectedTransactionId()), prefetch);

			_transactionItemForm.SetMandatoryFields(new List<int> { 3});
			_transactionItemForm.SetNumericFields(new List<int> { 3});
		}

		private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
		{
			foreach(DataGridViewRow row in dataGridView1.Rows)
			{
				var item = (TransactionItemEntity)row.DataBoundItem;
				if (item.ItemTypeId != 3)
				{
					row.Cells[laborCostDataGridViewTextBoxColumn.Index].ReadOnly = true;
					row.Cells[expensesDataGridViewTextBoxColumn.Index].ReadOnly = true;
				}
				else
				{
					row.Cells[laborCostDataGridViewTextBoxColumn.Index].ReadOnly = false;
					row.Cells[expensesDataGridViewTextBoxColumn.Index].ReadOnly = false;
				}
			}
		}
	}
}
